package fr.dauphine.spring.ctl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import fr.dauphine.spring.bo.Client;
import fr.dauphine.spring.dao.ClientDAO;

@Controller
@RequestMapping("client.html")
@SessionAttributes("client")
/* @SessionAttributes({"panier"}) */
public class ClientController {

	@Autowired
	private Validator clientValidator;

	@Autowired
	private ClientDAO clientDAO;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

	}

	@RequestMapping(method = RequestMethod.GET, params = {})
	public String affichage(ModelMap model) {
		model.addAttribute("client", new Client());

		return "client";
	}

	@RequestMapping(method = RequestMethod.GET, params = { "idClient" })
	public String affichage(ModelMap model, @RequestParam("idClient") String idClient) {
		try {
			Client client = clientDAO.getWithData(idClient);
			model.addAttribute("client", client);

			return "client";
		} catch (Exception ex) {
			ex.printStackTrace();
			return "erreur";
		}
	}

	@RequestMapping(params = "validation=Valider", method = RequestMethod.POST)
	public String validation(@ModelAttribute("client") Client client, BindingResult result,
			@RequestParam("fichier") MultipartFile fichier, ModelMap model) throws Exception {
		if (fichier != null && fichier.getSize() > 0) {
			client.setPhoto(fichier.getBytes());
			client.setPhotoType(fichier.getContentType());
		} else if (client.getId() != null && !client.getId().equals("")) {
			Client c = clientDAO.getWithData(client.getId());
			client.setPhoto(c.getPhoto());
			client.setPhotoType(c.getPhotoType());
		}
		clientValidator.validate(client, result);
		if (result.hasErrors()) {
			return "client";
		} else {
			clientDAO.save(client);
			model.addAttribute("client", client);

			return "redirect:adresse.html";
		}
	}

	@RequestMapping(params = "validation=Annuler", method = RequestMethod.POST)
	public String validation() {
		return "redirect:clients.html";
	}

}
